package demo2;
import java.util.Stack;
import java.util.Queue;
import java.util.LinkedList;

/**
 * 补二叉树笔记*/
public class BinaryTree {
    //创建树节点
    static class TreeNode{
        public char val;
        public TreeNode left;
        public TreeNode right;
        public TreeNode(char val) {
            this.val = val;
        }
    }
    //用于保存根节点
    //用于维护str的遍历
    public int i;
    public BinaryTree() {
        this.i = 0;
    }

    /**
     * 前序遍历创建二叉树*/
    public TreeNode preCreateTree(String str) {
        if(str==null || str.charAt(i)=='#') {
            i++;
            return null;
        }
        TreeNode node = new TreeNode(str.charAt(i));
        i++;
        node.left = preCreateTree(str);
        node.right = preCreateTree(str);
        return node;
    }

    /**
     * 前序遍历（递归实现）*/
    public void preOrder(TreeNode root) {
        if(root == null) {
            return;
        }
        System.out.print(root.val+" ");
        preOrder(root.left);
        preOrder(root.right);
    }

    /**
     * 中序遍历（递归实现）*/
    public void inOrder(TreeNode root) {
        if(root == null) {
            return;
        }
        inOrder(root.left);
        System.out.print(root.val+" ");
        inOrder(root.right);
    }

    /**
     * 后序遍历（递归实现）*/
    public void postOrder(TreeNode root) {
        if(root == null) {
            return;
        }
        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.val+" ");
    }

    /**
     * 前序遍历（迭代实现）
     * 二叉树遍历迭代实现主要依赖于栈结构*/
    public void preOrderIteration(TreeNode root) {
        if(root == null) {
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        TreeNode cur = null;
        while(!stack.isEmpty()) {
            cur = stack.pop();
            if(cur!=null) {
                System.out.print(cur.val+" ");
                stack.push(cur.right);
                stack.push(cur.left);
            }
        }
    }

    /**
     * 中序判断（迭代实现）*/
    public void inOrderIteration(TreeNode root) {
        if(root == null) {
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while(cur!=null || !stack.isEmpty()) {
            while(cur!=null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode tmp = stack.pop();
            System.out.print(tmp.val+" ");
            cur = tmp.right;
        }
    }

    /**
     * 后序判断（迭代实现）*/
    public void postOrderIteration(TreeNode root) {
        if(root == null) {
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while(cur!=null || !stack.isEmpty()) {

        }
    }
}
